import React, { Fragment, useState, useEffect } from 'react'
import PageList from './components/page-list'
import PageModel from './components/page-model'
import * as server from '../../services/navigation'

const useService = (initValue = []) => {
  const [list, setList] = useState(initValue)
  const [dataLoading, setDataLoading] = useState(false)

  const query = () => {
    setDataLoading(true)
    server.queryList().then(res => {
      setDataLoading(false)
      if (res.data) {
        setList(res.data.reverse())
      }
    })
  }

  useEffect(query, [])

  const addList = (item) => {
    server.addList(item).then(res => {
      if (res.code === 200) {
        query()
      }
    })
  }

  const modList = (item) => {
    server.modList(item).then(res => {
      if (res.code === 200) {
        query()
      }
    })
  }

  const removeList = (item) => {
    server.removeList(item).then(res => {
      if (res.code === 200) {
        query()
      }
    })
  }
  return { list, addList, modList, removeList, dataLoading }
}

function Page() {
  const { list, dataLoading, addList } = useService()
  const [modelVisible, setModelVisible] = useState(false)
  const [modelType, setModelType] = useState('create')
  const pageListProps = {
    data: list,
    loading: dataLoading,
    showModel() {
      setModelVisible(true)
      setModelType('create')
    }
  }

  const modalProps = {
    title: modelType === 'create' ? '添加导航信息' : '修改导航信息',
    width: 800,
    cancelText: '取消',
    okText: '确认',
    item: {},
    visible: modelVisible,
    handleCancel() {
      setModelVisible(false)
    },
    handleOk(item) {
      setModelVisible(false)
      addList(item)
    }
  }
  return (
    <Fragment>
      <PageList {...pageListProps} />
      {modelVisible && <PageModel {...modalProps} />}
    </Fragment>
  )
}

export default Page
